package com.gamecollection.snake.model.obj;

import com.gamecollection.snake.model.SnakeModel;
import com.gamecollection.snake.utils.GameUtils;

import java.awt.*;

/**
 * 蛇头对象
 */
public class HeadObj extends GameObj {
    
    // 方向 up down left right
    private String direction = "right";
    
    public HeadObj(Image img, int x, int y, SnakeModel model) {
        super(img, x, y, model);
    }
    
    /**
     * 改变方向
     */
    public void changeDirection(String newDirection) {
        switch (newDirection) {
            case "left":
                if (!"right".equals(direction)) {
                    direction = "left";
                    setImg(GameUtils.leftImg);
                }
                break;
            case "right":
                if (!"left".equals(direction)) {
                    direction = "right";
                    setImg(GameUtils.rightImg);
                }
                break;
            case "up":
                if (!"down".equals(direction)) {
                    direction = "up";
                    setImg(GameUtils.upImg);
                }
                break;
            case "down":
                if (!"up".equals(direction)) {
                    direction = "down";
                    setImg(GameUtils.downImg);
                }
                break;
        }
    }
    
    @Override
    public void update() {
        // 蛇身移动
        for (int i = model.getBodyObjList().size() - 1; i >= 1; i--) {
            BodyObj current = model.getBodyObjList().get(i);
            BodyObj previous = model.getBodyObjList().get(i - 1);
            current.setX(previous.getX());
            current.setY(previous.getY());
        }
        
        if (!model.getBodyObjList().isEmpty()) {
            BodyObj first = model.getBodyObjList().get(0);
            first.setX(this.getX());
            first.setY(this.getY());
        }
        
        // 蛇头移动
        switch (direction) {
            case "up":
                setY(getY() - getHeight());
                break;
            case "down":
                setY(getY() + getHeight());
                break;
            case "left":
                setX(getX() - getWidth());
                break;
            case "right":
                setX(getX() + getWidth());
                break;
        }
        
        // 越界处理
        if (getX() < 0) {
            setX(570);
        } else if (getX() > 570) {
            setX(0);
        } else if (getY() < 30) {
            setY(570);
        } else if (getY() > 570) {
            setY(30);
        }
    }
    
    public String getDirection() {
        return direction;
    }
    
    public void setDirection(String direction) {
        this.direction = direction;
    }
} 